package main

import (
	"fmt"
	consul_api "github.com/hashicorp/consul/api"
)

type Consul struct {
	client *consul_api.Client
}

// 服务发现 用来注册自己的服务端口给别的服务器调用和发现其他服务器
func InitConsul(host string, port int) *Consul {
	config := consul_api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", host, port)
	c, err := consul_api.NewClient(config)
	if err != nil {
		panic(err)
	}
	return &Consul{
		client: c,
	}

}

func (c *Consul) RegisterService(Name, Addr string, Port int, Tags ...string) error {
	return c.client.Agent().ServiceRegister(&consul_api.AgentServiceRegistration{
		ID:      Name,
		Name:    Name,
		Port:    Port,
		Tags:    Tags,
		Address: Addr,
		Check: &consul_api.AgentServiceCheck{
			Timeout:                        "5s",
			Interval:                       "10s",
			TCP:                            fmt.Sprintf("%v:%v", Addr, Port),
			DeregisterCriticalServiceAfter: "30s",
		},
	})
}

func (c *Consul) GetService(ID string) (service *consul_api.AgentService, err error) {
	service, _, err = c.client.Agent().Service(ID, &consul_api.QueryOptions{})
	return
}

func (c *Consul) GetService2(name string) {
	// 这里的name是服务名，底下可能有多个实例ID
	services, _, _ := c.client.Health().Service(name, "", false, &consul_api.QueryOptions{})
	for _, v := range services {
		fmt.Println(111111, v.Service.Address)
	}
}

func main() {
	var consul *Consul
	//注册consul服务地址
	Host := "127.0.0.1"
	Port := 8500
	consul = InitConsul(Host, Port)

	/*
		Server := "10.0.0.11:8900"
		Name := "go_maple"
		serverHost, err := strconv.Atoi(strings.Split(Server, ":")[1])
		if err != nil {
			panic(err)
		}

		err = Consul.RegisterService(Name, Host, serverHost)
		if err != nil {
			panic(err)
		}

	*/

	//获取服务
	res, err := consul.GetService("oms_v1")
	if err != nil {
		panic(err)
	}
	fmt.Println(res)

	consul.GetService2("oms")
}
